<template>
	<view class="page-container">
		<uni-section class="section-header" title="奖品管理" type="line">
			<template #right>
				<button class="action-button primary" size="mini" @click="handleAdd">
					<uni-icons class="icon" type="plus" size="16" color="#fff"></uni-icons>
					新增奖品
				</button>
			</template>
		</uni-section>

		<view class="prize-list">
			<view class="prize-item" v-for="(item, index) in list" :key="item._id || index"
				:style="{borderLeft: `6px solid ${item.bgColor}`}">
				<view class="prize-image" @click="handleUpload(index)">
					<image :src="item.img || '/static/default-prize.png'" mode="aspectFill" class="image"></image>
					<view class="upload-mask" v-if="!item.img">
						<uni-icons type="plus" size="24" color="#fff"></uni-icons>
						<text class="upload-text">添加图片</text>
					</view>
				</view>

				<view class="prize-content">
					<input class="prize-title" v-model="item.title" placeholder="请输入奖品名称"
						placeholder-class="placeholder" />

					<!-- 权重输入和概率显示 -->
					<view class="weight-section">
						<text class="weight-label">权重:</text>
						<input type="number" class="weight-input" v-model.number="item.weight" min="1"
							@input="calculateProbabilities" />
						<text class="probability">概率: {{ item.probability || '计算中...' }}%</text>
					</view>

					<view class="color-picker-group">
						<view class="color-picker-item">
							<text class="color-label">背景色</text>
							<view class="color-preview" :style="{backgroundColor: item.bgColor}"
								@click="handlePickColor(index, 'bgColor')"></view>
						</view>
						<view class="color-picker-item">
							<text class="color-label">文字色</text>
							<view class="color-preview" :style="{backgroundColor: item.color}"
								@click="handlePickColor(index, 'color')"></view>
						</view>
					</view>

					<view class="action-buttons">
						<button size="mini" class="action-button delete" @click="handleDel(index)">
							<uni-icons type="trash" size="16" color="#fff"></uni-icons>
							删除
						</button>
						<button size="mini" class="action-button save" @click="handleSubmit(index)">
							<uni-icons type="checkmarkempty" size="16" color="#fff"></uni-icons>
							保存
						</button>
					</view>
				</view>
			</view>
		</view>

		<view class="footer-actions" v-if="list.length > 0">
			<button class="confirm-button" @click="handleOk">
				<uni-icons type="checkmarkempty" size="20" color="#fff"></uni-icons>
				完成编辑
			</button>
		</view>

		<yq-color-picker ref="colorPicker" class="my-picker" :color="colorPickerColor" @confirm="confirm" />
		<ver />
	</view>
</template>

<script setup>
	import ver from '@/components/ver.vue'
	import {
		ref,
		onMounted,
		watch
	} from 'vue';
	import {
		getPrize,
		addPrize,
		updatePrize,
		deletePrize
	} from '@/api/prize.js';

	const colorPicker = ref(null);
	const colorPickerColor = ref('');
	const colorPickerIndex = ref(0);
	const colorPickerKey = ref('');
	const list = ref([]);

	// 计算所有奖品的概率
	const calculateProbabilities = () => {
		const totalWeight = list.value.reduce((sum, item) => sum + (item.weight || 1), 0);
		list.value.forEach(item => {
			const probability = (item.weight / totalWeight) * 100;
			item.probability = probability.toFixed(2);
		});
	};

	// 监听列表变化重新计算概率
	watch(list, calculateProbabilities, {
		deep: true
	});

	// 颜色选择确认
	const confirm = (color) => {
		list.value[colorPickerIndex.value][colorPickerKey.value] = color;
	};

	// 上传图片
	const handleUpload = async (index) => {
		try {
			const res = await uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera']
			});

			const tempFilePath = res.tempFilePaths[0];
			const uploadRes = await uniCloud.uploadFile({
				filePath: tempFilePath,
				cloudPath: `prize-images/${Date.now()}.jpg`
			});

			list.value[index].img = uploadRes.fileID;
			uni.showToast({
				title: '上传成功',
				icon: 'success'
			});
		} catch (err) {
			uni.showToast({
				title: '上传失败: ' + err.message,
				icon: 'error'
			});
		}
	};

	// 选择颜色
	const handlePickColor = (index, key) => {
		colorPickerIndex.value = index;
		colorPickerKey.value = key;
		colorPickerColor.value = list.value[index][key];
		colorPicker.value.open();
	};

	// 删除奖品
	const handleDel = async (index) => {
		try {
			const {
				confirm: isConfirm
			} = await uni.showModal({
				title: '删除确认',
				content: '确定要删除这个奖品吗?',
				confirmColor: '#ff6b6b'
			});

			if (!isConfirm) return;

			const item = list.value[index];
			if (item._id) {
				await deletePrize(item._id);
			}

			list.value.splice(index, 1);
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			});
		} catch (error) {
			uni.showToast({
				title: error.message || '删除失败',
				icon: 'error'
			});
		}
	};

	// 新增奖品
	const handleAdd = () => {
		list.value.push({
			img: '',
			title: '',
			bgColor: '#4e7af0',
			color: '#FFFFFF',
			weight: 1, // 默认权重为1
			probability: '0.00', // 初始概率
			_id: null
		});
	};

	// 保存奖品
	const handleSubmit = async (index) => {
		const item = list.value[index];

		if (!item.title.trim()) {
			return uni.showToast({
				title: '请输入奖品名称',
				icon: 'none'
			});
		}

		try {
			// 准备保存的数据，包含权重
			const prizeData = {
				img: item.img,
				title: item.title,
				bgColor: item.bgColor,
				color: item.color,
				weight: item.weight || 1
			};

			if (item._id) {
				await updatePrize(item._id, prizeData);
				uni.showToast({
					title: '更新成功',
					icon: 'success'
				});
			} else {
				const {
					id
				} = await addPrize(prizeData);
				item._id = id;
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
			}
		} catch (error) {
			uni.showToast({
				title: error.message || '操作失败',
				icon: 'error'
			});
		}
	};

	// 完成编辑
	const handleOk = () => {
		uni.navigateBack();
	};

	// 初始化加载数据
	onMounted(async () => {
		try {
			const res = await getPrize();
			list.value = res.map(item => ({
				...item,
				img: item.img || '',
				title: item.title || '',
				bgColor: item.bgColor || '#4e7af0',
				color: item.color || '#FFFFFF',
				weight: item.weight || 1, // 确保有权重值
				_id: item._id || null
			}));

			// 计算概率
			calculateProbabilities();
		} catch (error) {
			uni.showToast({
				title: error.message || '加载失败',
				icon: 'error'
			});
		}
	});
</script>

<style lang="scss" scoped>
	.my-picker {
		width: 0;
		height: 0;
		overflow: auto;
	}

	.page-container {
		padding: 20rpx;
		padding-bottom: 200rpx;
		box-sizing: border-box;
		min-height: 100vh;
		background-color: #f5f7fa;

		.section-header {
			margin-bottom: 30rpx;

			.action-button {
				display: flex;
				align-items: center;
				padding: 0 24rpx;
				font-size: 26rpx;
				border-radius: 50rpx;
				transition: all 0.2s;
				box-shadow: 0 4rpx 12rpx rgba(78, 122, 240, 0.3);

				.icon {
					position: relative;
					top: 2rpx;
					margin-right: 4rpx;
				}

				&.primary {
					background-color: #4e7af0;
					color: #fff;

					&:active {
						transform: translateY(2rpx);
						box-shadow: 0 2rpx 6rpx rgba(78, 122, 240, 0.3);
					}
				}
			}
		}

		.prize-list {
			.prize-item {
				display: flex;
				padding: 30rpx;
				margin-bottom: 24rpx;
				background-color: #fff;
				border-radius: 16rpx;
				box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.05);
				transition: all 0.3s ease;
				position: relative;
				overflow: hidden;

				&::before {
					content: '';
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0) 100%);
					pointer-events: none;
				}

				&:active {
					transform: translateY(2rpx);
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
				}

				.prize-image {
					position: relative;
					width: 160rpx;
					height: 160rpx;
					margin-right: 30rpx;
					border-radius: 12rpx;
					overflow: hidden;
					background-color: #f1f3f5;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-shrink: 0;

					.image {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}

					.upload-mask {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						background-color: rgba(0, 0, 0, 0.4);
						color: #fff;

						.upload-text {
							font-size: 24rpx;
							margin-top: 10rpx;
							color: rgba(255, 255, 255, 0.9);
						}
					}
				}

				.prize-content {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.prize-title {
						width: 100%;
						padding: 16rpx 0;
						font-size: 32rpx;
						font-weight: 500;
						color: #333;
						border-bottom: 1rpx solid #eee;
						margin-bottom: 24rpx;
						transition: all 0.2s;

						&:focus {
							border-bottom-color: #4e7af0;
						}

						.placeholder {
							color: #adb5bd;
						}
					}

					/* 权重输入区域样式 */
					.weight-section {
						display: flex;
						align-items: center;
						margin-bottom: 20rpx;
						padding: 10rpx 0;
						border-bottom: 1px solid #f0f0f0;

						.weight-label {
							font-size: 26rpx;
							color: #666;
							margin-right: 16rpx;
							white-space: nowrap;
						}

						.weight-input {
							width: 120rpx;
							padding: 8rpx 16rpx;
							border: 1px solid #e0e0e0;
							border-radius: 8rpx;
							font-size: 26rpx;
							text-align: center;
							margin-right: 20rpx;

							&:focus {
								border-color: #4e7af0;
								outline: none;
							}
						}

						.probability {
							font-size: 26rpx;
							color: #ff6b6b;
							font-weight: bold;
							white-space: nowrap;
						}
					}

					.color-picker-group {
						display: flex;
						margin-bottom: 24rpx;

						.color-picker-item {
							display: flex;
							align-items: center;
							margin-right: 40rpx;

							.color-label {
								font-size: 26rpx;
								color: #666;
								margin-right: 16rpx;
							}

							.color-preview {
								width: 60rpx;
								height: 60rpx;
								border-radius: 12rpx;
								border: 2rpx solid #f1f3f5;
								cursor: pointer;
								transition: all 0.2s;
								box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

								&:active {
									transform: scale(0.95);
								}
							}
						}
					}

					.action-buttons {
						display: flex;
						flex-direction: row-reverse;

						.action-button {
							display: flex;
							align-items: center;
							justify-content: center;
							padding: 0 34rpx;
							font-size: 26rpx;
							border-radius: 50rpx;
							transition: all 0.2s;
							box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
							margin: 0 20rpx 0 0;

							&:active {
								transform: translateY(2rpx);
								box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
								opacity: 0.9;
							}

							.uni-icons {
								margin-right: 8rpx;
							}

							&.save {
								background-color: #51cf66;
								color: #fff;
							}

							&.delete {
								background-color: #ff6b6b;
								color: #fff;
							}
						}
					}
				}
			}
		}

		.footer-actions {
			position: fixed;
			bottom: 60rpx;
			left: 0;
			right: 0;
			padding: 0 40rpx;
			display: flex;
			justify-content: center;

			.confirm-button {
				width: 80%;
				padding: 0;
				background: linear-gradient(135deg, #4e7af0, #6a5acd);
				color: #fff;
				border-radius: 50rpx;
				font-size: 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 6rpx 18rpx rgba(78, 122, 240, 0.4);
				transition: all 0.2s;

				.uni-icons {
					margin-right: 10rpx;
				}

				&:active {
					transform: translateY(2rpx);
					box-shadow: 0 3rpx 9rpx rgba(78, 122, 240, 0.4);
				}
			}
		}
	}
</style>